//
//  NewDetailController.m
//  Cunli
//
//  Created by lilubin on 15/6/12.
//  Copyright (c) 2015年 lilubin. All rights reserved.
//

#import "NewDetailController.h"
#import "NewsDetailModel_yy.h"
#import "NSString+MD5.h"
#import "MyDataService.h"
#import "UIViewExt.h"
#import "Config.h"
#import "HYActivityView.h"
#import "ReportDetailVC.h"
#import "MBProgressHUD.h"
#import "MaxResponseButton.h"
#import "IMYWebView.h"
#import "UIColor+expanded.h"

#import "UMSocial.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height

@interface NewDetailController ()

@property (nonatomic, strong) NewsDetailModel_yy *newsModel; //新闻model

@property (nonatomic, strong) UIWebView *detailWebView;   //新闻详情webview

@property (nonatomic, strong) HYActivityView *activityView; //弹出视图

@end

@implementation NewDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    //    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.title = @"详情";
    [self setAttributesAboutWebView];
    [self loadNewsData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)loadNewsData
{
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:3];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:_itemID forKey:@"itemid"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    
    [MyDataService requestURL:@"newsdetail.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        NSString *response = [result objectForKey:@"response"];
        if ([response isEqualToString:@"error"]) {
            NSDictionary *errorDic = [result objectForKey:@"error"];
            NSString *text = errorDic[@"text"];
            [Config showHUDWithText:text andImage:@"error"];
        }
        else
        {
            NSDictionary *newsinfo = result[@"newsinfo"];
            //            _newsModel = [[NewsDetailModel alloc] initWithDataDic:newsinfo];
            _newsModel = [NewsDetailModel_yy yy_modelWithJSON:newsinfo];
            NSString *testURLStr = [NSString stringWithFormat:@"<html><body><h3 align='left' style='margin-bottom:0px;'>%@</h3><p align='left' style='color:#777777; margin-top:0px;'>%@&nbsp;%@</p>%@<br/><br/></body></html>", _newsModel.title, _newsModel.addtime, _newsModel.author, _newsModel.content];
            [_detailWebView loadHTMLString:testURLStr baseURL:nil];
        }
    } failureAction:^{
        [Config showHUDWithText:@"网络错误" andImage:@"error"];
    }];
    
}

- (void)setAttributesAboutWebView
{
    CGRect newFrame = self.view.frame;
    CGFloat newHeight = newFrame.size.height-64;
    newFrame.size.height = newHeight;
#pragma mark - old fun
    
    _detailWebView = [[UIWebView alloc] initWithFrame:newFrame];
    _detailWebView.delegate = self;
    _detailWebView.scrollView.delegate = self;
    _detailWebView.scrollView.bounces = NO;
    _detailWebView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:_detailWebView];
    
    /*
     _detailWebView = [[IMYWebView alloc] initWithFrame:newFrame];
     _detailWebView.delegate = self;
     _detailWebView.scrollView.delegate = self;
     _detailWebView.scrollView.bounces = NO;
     _detailWebView.translatesAutoresizingMaskIntoConstraints = NO;
     [self.view addSubview:_detailWebView];
     
     if(_detailWebView.usingUIWebView)
     {
     NSLog(@">>>UIWebView");
     }
     else
     {
     NSLog(@">>>WKWebView");
     }
     */
    /*
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 28, 28);
    [leftBtn setImage:[UIImage imageNamed:@"regback01"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    leftBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftBarItem;
    */
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 25, 20);
    [rightBtn setImage:[UIImage imageNamed:@"nav_right_share"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(popAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightBarItem;
    
}

- (void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)popAction:(UIButton *)button
{
    __weak typeof(self) weakSelf = self;
    
    if (!self.activityView) {
        self.activityView = [[HYActivityView alloc] initWithTitle:@"分享到" referView:self.view];
        
        //横屏会变成一行6个, 竖屏无法一行同时显示6个, 会自动使用默认一行4个的设置.
        self.activityView.numberOfButtonPerLine = 6;
        
        ButtonView *bv = [[ButtonView alloc]initWithText:@"QQ" image:[UIImage imageNamed:@"cunli_qqFriend"] handler:^(ButtonView *buttonView){
            [UMSocialData defaultData].extConfig.qqData.qqMessageType = UMSocialQQMessageTypeDefault;
            [UMSocialData defaultData].extConfig.qqData.title = weakSelf.newsModel.title;
            [UMSocialData defaultData].extConfig.qqData.url = weakSelf.newsModel.share_url;
            
            [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToQQ] content:weakSelf.newsModel.share_url image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response) {
                //                NSLog(@"QQ分享成功");
                if (response.responseCode == UMSResponseCodeSuccess)
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf postPointGetRequestWithString:@"4"];
                    });
                }
            }];
            
        }];
        [self.activityView addButtonView:bv];
        
        bv = [[ButtonView alloc]initWithText:@"QQ空间" image:[UIImage imageNamed:@"cunli_qqZone"] handler:^(ButtonView *buttonView){
            [UMSocialData defaultData].extConfig.qqData.qqMessageType = UMSocialQQMessageTypeDefault;
            [UMSocialData defaultData].extConfig.qzoneData.title = weakSelf.newsModel.title;
            [UMSocialData defaultData].extConfig.qzoneData.url = weakSelf.newsModel.share_url;
            
            [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToQzone] content:weakSelf.newsModel.title image:[UIImage imageNamed:@"aboutApp01.png"] location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response) {
                if (response.responseCode == UMSResponseCodeSuccess) {
                    //                    NSLog(@"QQ空间分享成功");
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf postPointGetRequestWithString:@"3"];
                    });
                    
                }
            }];
            
        }];
        [self.activityView addButtonView:bv];
        
        bv = [[ButtonView alloc]initWithText:@"微信" image:[UIImage imageNamed:@"cunli_wechatFriend"] handler:^(ButtonView *buttonView){
            
            [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeWeb;
            [UMSocialData defaultData].extConfig.wechatSessionData.url = weakSelf.newsModel.share_url;
            [UMSocialData defaultData].extConfig.title = weakSelf.newsModel.title;
            
            [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatSession] content:weakSelf.newsModel.title image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response) {
                //                NSLog(@"分享成功");
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf postPointGetRequestWithString:@"1"];
                });
                
            }];
        }];
        [self.activityView addButtonView:bv];
        
        bv = [[ButtonView alloc]initWithText:@"朋友圈" image:[UIImage imageNamed:@"cunli_wechatTimeline"] handler:^(ButtonView *buttonView){
            [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeWeb;
            [UMSocialData defaultData].extConfig.wechatTimelineData.url = weakSelf.newsModel.share_url;
            [UMSocialData defaultData].extConfig.title = weakSelf.newsModel.title;
            
            [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatTimeline] content:_newsModel.title image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response) {
                //                NSLog(@"分享成功");
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf postPointGetRequestWithString:@"2"];
                });
                
            }];
            
        }];
        [self.activityView addButtonView:bv];
        
        bv = [[ButtonView alloc]initWithText:@"收藏" image:[UIImage imageNamed:@"cunli_favorite"] handler:^(ButtonView *buttonView){
            [weakSelf doFavoriteAction];
        }];
        [self.activityView addButtonView:bv];
        
        bv = [[ButtonView alloc]initWithText:@"刷新" image:[UIImage imageNamed:@"cunli_refresh"] handler:^(ButtonView *buttonView){
            [weakSelf doRefreshAction];
        }];
        [self.activityView addButtonView:bv];
        
        bv = [[ButtonView alloc]initWithText:@"举报" image:[UIImage imageNamed:@"cunli_report"] handler:^(ButtonView *buttonView){
            [weakSelf doReportAction];
        }];
        [self.activityView addButtonView:bv];
        
    }
    if (![Config isShield]) {
        [self.activityView show];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您已被村联络员屏蔽在该村的发言。如需申诉,请到“我-消息-通讯录”中与联络员进行联系" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
}

- (void)postPointGetRequestWithString:(NSString *)str
{
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:4];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:_newsModel.itemid forKey:@"item_id"];
    [CheckParams setObject:_newsModel.item_mid forKey:@"item_mid"];
    [CheckParams setObject:str forKey:@"channel"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    
    [MyDataService requestURL:@"app_point_share.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result)
     {
         NSLog(@"In newsDetailController result:%@", result);
         
         if ([result[@"response"] isEqualToString:@"app_point_share"])
         {
             NSLog(@"获取积分成功");
         }
     } failureAction:^{
         NSLog(@"获取积分失败");
     }];
}

//收藏文章详情方法
- (void)doFavoriteAction
{
    //    NSLog(@"点击收藏");
    NSMutableDictionary *CheckParams = [NSMutableDictionary dictionaryWithCapacity:5];
    [CheckParams setObject:[Config getOwnUserID] forKey:@"userid"];
    [CheckParams setObject:self.newsModel.itemid forKey:@"itemid"];
    [CheckParams setObject:self.newsModel.item_mid forKey:@"item_mid"];
    [CheckParams setObject:@"1" forKey:@"type"];
    
    NSString *resultSign = [NSString getSignFromParam:CheckParams andSession:[Config getOwnSession]];
    [CheckParams setObject:resultSign forKey:@"sign"];
    [MyDataService requestURL:@"add_favorite.php" httpMethod:@"GET" params:CheckParams fileDatas:nil complection:^(id result) {
        
        MBProgressHUD *hud = [Config createHUD];
        hud.mode = MBProgressHUDModeCustomView;
        if ([result[@"response"] isEqualToString:@"add_favorite"]) {
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
            hud.labelText = @"收藏成功";
        }else
        {
            NSString *reason = [result[@"error"] objectForKey:@"text"];
            hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"done"]];
            hud.labelText = reason;
        }
        [hud hide:YES afterDelay:1];
        
    } failureAction:^{
        MBProgressHUD *hud = [Config createHUD];
        hud.mode = MBProgressHUDModeCustomView;
        hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]];
        hud.labelText = @"收藏失败";
        [hud hide:YES afterDelay:1];
        
    }];
    
}

//刷新文章详情方法
- (void)doRefreshAction
{
    //    NSLog(@"刷新");
}

//举报文章方法
- (void)doReportAction
{
    ReportDetailVC *reportVC = [[ReportDetailVC alloc] init];
    reportVC.itemid = self.newsModel.itemid;
    reportVC.m_itemid = self.newsModel.item_mid;
    [self.navigationController pushViewController:reportVC animated:YES];
}

#pragma mark - <UIWebViewDelegate>

- (void)webViewDidFinishLoad:(IMYWebView *)webView
{
    
    CGFloat contentHeight = webView.scrollView.contentSize.height;
    //    CGFloat contentWidth = webView.scrollView.contentSize.width;
    CGFloat yPosition = contentHeight - 30;
    
    
    UIImageView *readImgView = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth-190, yPosition, 16, 16)];
    [readImgView setImage:[UIImage imageNamed:@"readNumImage"]];
    [_detailWebView.scrollView addSubview:readImgView];
    
    UILabel *readNumLabel = [[UILabel alloc] initWithFrame:CGRectMake(readImgView.right+3, yPosition, 70, 16)];
    NSString *text = [NSString stringWithFormat:@"阅读(%@)", _newsModel.hits];
    [readNumLabel setFont:[UIFont systemFontOfSize:15]];
    [readNumLabel setTextColor:[UIColor colorWithHexString:@"0x999999"]];
    [readNumLabel setText:text];
    [readNumLabel setTextAlignment:NSTextAlignmentLeft];
    if (_newsModel.hits.length > 3) {
        [readNumLabel setText:@"99+"];
    }
    [_detailWebView.scrollView addSubview:readNumLabel];
    
    UIImageView *goodImgView = [[UIImageView alloc] initWithFrame:CGRectMake(readNumLabel.right+10, yPosition, 16, 16)];
    [goodImgView setImage:[UIImage imageNamed:@"goodNumImage"]];
    goodImgView.tag = 1070;
    [_detailWebView.scrollView addSubview:goodImgView];
    
    MaxResponseButton *goodBtn = [[MaxResponseButton alloc] initWithFrame:CGRectMake(goodImgView.right+3, yPosition, 70, 16)];
    goodBtn.selected = NO;
    [goodBtn setTitleColor:[UIColor colorWithHexString:@"0x999999"] forState:UIControlStateNormal];
    [goodBtn.titleLabel setFont:[UIFont systemFontOfSize:15]];
    NSString *goodText = [NSString stringWithFormat:@"赞(%@)", _newsModel.look];
    NSInteger goodNum = [_newsModel.look integerValue];
    NSString *haveGoodText = [NSString stringWithFormat:@"赞(%ld)", goodNum+1];
    [goodBtn setTitle:goodText forState:UIControlStateNormal];
    [goodBtn setTitle:haveGoodText forState:UIControlStateHighlighted];
    goodBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    goodBtn.backgroundColor = [UIColor clearColor];
    goodBtn.tag = 200;
    [_detailWebView.scrollView addSubview:goodBtn];
    [goodBtn addTarget:self action:@selector(goodBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goodImgAction)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    goodImgView.userInteractionEnabled = YES;
    [goodImgView addGestureRecognizer:tap];
}

- (void)goodImgAction
{
    MaxResponseButton *goodBtn = [_detailWebView viewWithTag:200];
    [self goodBtnAction:goodBtn];
}

- (void)goodBtnAction:(MaxResponseButton *)button
{
    if (button.selected) {
        [Config showHUDWithText:@"您已点过赞" andImage:@"done"];
        return;
    }
    NSInteger goodNum = [_newsModel.look integerValue];
    NSString *haveGoodText = [NSString stringWithFormat:@"赞(%ld)", goodNum+1];
    UIButton *goodBtn = (UIButton *)[_detailWebView viewWithTag:200];
    [goodBtn setTitle:haveGoodText forState:UIControlStateNormal];
    
    NSMutableDictionary *praiseDic = [NSMutableDictionary dictionaryWithCapacity:3];
    [praiseDic setObject:[Config getOwnUserID] forKey:@"userid"];
    [praiseDic setObject:_itemID forKey:@"itemid"];
    NSString *resultSign = [NSString getSignFromParam:praiseDic andSession:[Config getOwnSession]];
    [praiseDic setObject:resultSign forKey:@"sign"];
    
    UIImageView *imgView = (UIImageView *)[_detailWebView viewWithTag:1070];
    [imgView setImage:[UIImage imageNamed:@"goodNumImage_click"]];
    [MyDataService requestURL:@"newspraise.php" httpMethod:@"GET" params:praiseDic fileDatas:nil complection:^(id result) {
        //        NSLog(@"NewsPraise result:%@", result);
        NSString *response = result[@"response"];
        if ([response isEqualToString:@"newspraise"]) {
            [self showHUDWithText:@"点赞成功" andImage:@"done"];
        }else if([response isEqualToString:@"error"])
        {
            NSDictionary *dic = result[@"error"];
            NSString *reason = dic[@"text"];
            [self showHUDWithText:reason andImage:@"error"];
        }
    } failureAction:^{
        [self showHUDWithText:@"点赞失败" andImage:@"error"];
    }];
    button.selected = YES;
    
}

-(void)dealloc
{
    _detailWebView = nil;
}

- (void)showHUDWithText:(NSString *)str andImage:(NSString *)imgStr
{
    MBProgressHUD *hud = [Config createHUD];
    hud.mode = MBProgressHUDModeCustomView;
    hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imgStr]];
    hud.labelText = str;
    [hud hide:YES afterDelay:1];
}



@end
